package com.haiertvbic.tvnow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.haiertvbic.timeline.MainActivity;
import com.haiertvbic.tvnow.baseactivity.SwitchActivity;
import com.haiertvbic.tvnow.model.ChannelPackage;
import com.haiertvbic.tvnow.model.ProgramDetail;
import com.haiertvbic.tvnow.model.TVChannel;
import com.haiertvbic.tvnow.model.UpdateInfo;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.pop.PipPop;
import com.haiertvbic.tvnow.protocol.CAEProtocol;
import com.haiertvbic.tvnow.testblock.Function;
import com.haiertvbic.tvnow.testblock.TestData;
import com.haiertvbic.tvnow.util.Constant;
import com.haiertvbic.tvnow.util.InitApplication;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.SPUtil;
import com.haiertvbic.tvnow.widget.PipCache;
import com.haiertvbic.tvnow.widget.RealTime;
import com.haiertvbic.tvnow.widget.RealTimePictrue;

public class TVNOWMainActivity extends SwitchActivity {
	protected static final int SHOW_OPERATION_MANUAL = 10001;
	protected static final int UPDATE_APP_TRUE = 10002;
	protected static final int NOTIFY_ADAPTER_DATA_CHANGED = 10003;
	private Activity context = TVNOWMainActivity.this;

	private ListView channelsLV;
	private TextView loading;
	private ArrayList<View> itemViews = new ArrayList<View>();
	private ImageView operationM;
	private ImageView noNetwork;

	// 要获取的频道数量
	private int CHANNEL_COUNT = 5;
	private Map<String, ArrayList<TVChannel>> mapChannels = new HashMap<String, ArrayList<TVChannel>>();
	private Map<String, String> currentGroup = new HashMap<String, String>();
	private int currentFive = 0;
	private ArrayList<TVChannel> channelList;
	private Handler myHandler;
	private boolean canToNext;
	private boolean ManualToNext = true;

	// ==========截屏定时更新=================
	private ArrayList<RealTime> realTimeList = new ArrayList<RealTime>();
	private ScreenShotAdapter adapter = new ScreenShotAdapter();
	// 控制轮循pip动画新图显示
	public static View childView;
	public static PipPop pip;
	private int which;
	private RealTimePictrue pictrueTask;

	@Override
	public void findView() {
		setContentView(R.layout.activity1_channellist);
		channelsLV = (ListView) findViewById(R.id.common_lv);
		loading = (TextView) findViewById(R.id.loading_tv);
		noNetwork = (ImageView) findViewById(R.id.no_network);
		TextView version = (TextView) findViewById(R.id.version);
		String versionS = "V";
		try {
			PackageInfo pinfo = getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			versionS = versionS + pinfo.versionName;
			versionS = versionS + "(debug)";
		} catch (NameNotFoundException e) {
			versionS = context.getString(R.string.failed_version);
			e.printStackTrace();
		}
		version.setText(versionS);
		operationM = (ImageView) findViewById(R.id.operation_manual);
	}

	@Override
	public void setDataSetup() {
		InitApplication.initParmas(context);
		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case NOTIFY_ADAPTER_DATA_CHANGED:
					adapter.notifyDataSetChanged();
					break;
				case UPDATE_APP_TRUE:
					updateAPKDialogShow(msg);
					break;
				case SHOW_OPERATION_MANUAL:
					ManualToNext = true;
					operationM.setVisibility(View.GONE);
					changeSelectedItemColor(channelsLV.getSelectedView());
					focusToChannel();
					break;

				default:
					break;
				}
				super.handleMessage(msg);
			}

			private void updateAPKDialogShow(Message msg) {
				final UpdateInfo updateInfo = (UpdateInfo) msg.obj;
				Builder dialog = new AlertDialog.Builder(context);
				String title = getString(R.string.app_name) + " "
						+ getString(R.string.find_new_apk);
				dialog.setTitle(title);
				String apkDes = updateInfo.getDesc();
				// apkDes = getString(R.string.apk_description);
				dialog.setMessage(apkDes);
				dialog.setCancelable(false);
				dialog.setPositiveButton(R.string.update_the_apk,
						new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// 调用下载接口
								// DownloadTask down = new DownloadTask(
								// context, updateInfo);
								// down.execute();
								PackageManager pm = getPackageManager();
								Intent intent = pm
										.getLaunchIntentForPackage("com.haier.appstore.activity");
								startActivity(intent);
								dialog.dismiss();
							}
						});
				dialog.setNegativeButton(R.string.not_update_the_apk,
						new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});

				dialog.show();
			}
		};
		new ChannelAsyncTask().execute();
		focusToOperationManual();
	}

	/**
	 * 在第一屏的最上层蒙上这张整图，持续5秒钟后自动消失。并且使用shareperference记录标识，从第二次开始就不再显示这张图，
	 * 这是一张用户操作向导图
	 */
	private void focusToOperationManual() {
		if (SPUtil.isUserManualLoad(context)) {
			ManualToNext = false;
			operationM.setVisibility(View.VISIBLE);
			myHandler.sendEmptyMessageDelayed(SHOW_OPERATION_MANUAL, 1000 * 15);
			Editor share = context.getSharedPreferences("isLoad",
					Context.MODE_PRIVATE).edit();
			share.putBoolean("isLoad", false);
			share.commit();
		} else {
			operationM.setVisibility(View.GONE);
			focusToChannel();
		}
	}

	private void focusToChannel() {
		channelsLV.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				Constant.CHANNELID = Integer.valueOf(channelList.get(position)
						.getChannel_id());
				which = position;
				dismissPop();
				changeSelectedItemColor(view);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

	}

	class ViewHodler {

		// 无网络的图标
		ImageView noNet;
		// 实时节目截图
		ImageView screenShot;
		// 有网络但无截图
		ImageView netButNoPictrue;
		LinearLayout programBackground;
		// 该频道当前播出的节目
		TextView programName;
		// 节目还剩多少时间播完
		TextView startTime;
		// 节目所在频道
		TextView channelName;
		ProgressBar grogressBar;
	}

	private void dismissPop() {
		if (pip != null) {
			pip.dismissPop();
			pip = null;
			PipCache.pipListMap = null;
		}
	}

	/**
	 * 得倒那个返回的view并把颜色改了
	 * 
	 * @param view
	 */
	private void changeSelectedItemColor(View view) {
		channelsLV.requestFocus();
		childView = view;
		if (view != null && !itemViews.contains(view)) {
			itemViews.add(view);
		}
		ViewHodler holder = new ViewHodler();
		for (int i = 0; i < itemViews.size(); i++) {
			if (view != null && itemViews.get(i) == view
					&& view.getTag() != null) {
				holder = (ViewHodler) view.getTag();
				holder.programBackground.setVisibility(View.VISIBLE);
				holder.programBackground
						.setBackgroundResource(R.color.red_color);
				holder.programName.setTextColor(getResources().getColor(
						R.color.white_color));// 白色
				holder.startTime.setTextColor(Color.WHITE);
			} else {
				if (itemViews.get(i) != null) {
					holder = (ViewHodler) itemViews.get(i).getTag();
					holder.programBackground.setVisibility(View.GONE);
					holder.programName.setTextColor(0x00FFFFFF);
					// 不被选中时的字颜色
					holder.startTime.setTextColor(0x00FFFFFF);
				}
				// 不被选中时的字颜色
			}
		}
	}

	class ChannelAsyncTask extends AsyncTask<Void, Void, Void> {

		private ChannelPackage channelPackage;

		@Override
		protected Void doInBackground(Void... params) {
			UpdateInfo updateInfo = EPGWeb.getUpdateInfo(context);
			if (updateInfo != null && updateInfo.getIsDown() != null
					&& updateInfo.getIsDown().equals("true")) {
				Message msg = Message.obtain();
				msg.obj = updateInfo;
				msg.what = UPDATE_APP_TRUE;
				myHandler.sendMessage(msg);
			}
			channelPackage = CAEProtocol.getFavChannel(1, CHANNEL_COUNT);
			if (Function.testData.get("channellist")) {
				channelPackage = TestData.getTestChannelData(channelPackage);
			}
			// ==============拆分数据=============================
			if (channelPackage != null) {
				channelList = channelPackage.getChannels();
				int mapsize = getChannelGroupByChannelLength(channelList.size());
				int i = 0;
				for (int group = 0; group < mapsize; group++) {
					ArrayList<TVChannel> temp5Channel = new ArrayList<TVChannel>();
					for (; i < channelList.size() && temp5Channel.size() != 5; i++) {
						temp5Channel.add(channelList.get(i));
					}
					if (temp5Channel.size() > 0) {
						mapChannels.put(group + "", temp5Channel);
					}
				}
			}

			return null;
		}

		/**
		 * 根据频道长度得到要分为几组
		 * 
		 * @param size
		 * @return
		 */
		private int getChannelGroupByChannelLength(int size) {
			int mapsize = size / 5;
			if (mapsize == 0) {
				mapsize = 1;
			} else if ((size % 5) != 0) {
				mapsize = mapsize + 1;
			}
			return mapsize;
		}

		@Override
		protected void onPostExecute(Void result) {

			if (channelPackage == null) {
				// 获取数据失败
				Toast.makeText(context,
						getString(R.string.get_chann_data_failed),
						Toast.LENGTH_LONG).show();
			} else if (channelPackage.getReturnCode() == CAEProtocol.DB_ERROR_1
					|| channelPackage.getReturnCode() == CAEProtocol.DB_ERROR_2) {
				// 操作数据库失败
				Toast.makeText(context, getString(R.string.db_error),
						Toast.LENGTH_LONG).show();
			} else if (channelPackage.getReturnCode() == CAEProtocol.NOT_SURE_ERROR) {
				// 发生未知错误
				Toast.makeText(context,
						getString(R.string.Indeterminate_error),
						Toast.LENGTH_LONG).show();
			} else if (channelPackage.getReturnCode() == CAEProtocol.GET_FAVCHAS_SUC
					|| channelPackage.getReturnCode() == CAEProtocol.GET_FAVCHAS_SUC_2) {
				if (mapChannels.size() > 0) {
					// 初始化定时器
					loadCurrentGroup("0");
					channelsLV.setAdapter(adapter);
					channelsLV.requestFocus();
					channelsLV.setVisibility(View.VISIBLE);
					loading.setVisibility(View.GONE);
					canToNext = true;
				} else {
					channelsLV.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.get_chann_data_failed);
				}
			}
			super.onPostExecute(result);
		}
	}

	/**
	 * 将当前所选的频道组数赋值
	 * 
	 * @param string
	 */
	private void loadCurrentGroup(String string) {
		channelList = mapChannels.get(string);
		if (currentGroup.get("currentGroup") != null) {
			currentGroup.remove("currentGroup");
		}
		currentGroup.put("currentGroup", string);
		// 初始化定时器
		executeTime();
		channelsLV.setAdapter(adapter);
		channelsLV.requestFocus();
	}

	private void executeTime() {
		exitScreen();
		SLog.d(TAG, "==realTimeList.size()==" + realTimeList.size());
		for (int i = 0; channelList != null && i < channelList.size(); i++) {
			int cid = channelList.get(i).getChannel_id();
			RealTime real = new RealTime(context, cid);
			realTimeList.add(real);
			new RealTimePictrue(adapter, real, context).getSinglePic();
		}
		if (realTimeList.size() > 0) {
			pictrueTask = new RealTimePictrue(adapter, realTimeList, context);
			pictrueTask.getPic();
		}
	}

	/**
	 * 停止定时器
	 */
	private void exitScreen() {
		realTimeList.clear();
		if (pictrueTask != null) {
			pictrueTask.timeStop();
		}
	}

	@Override
	protected void onStop() {
		// SharedPreferences shareData = context.getSharedPreferences("isLoad",
		// Context.MODE_PRIVATE);
		// String start = shareData.getString(Constant.toOtherApk, "null");
		// SLog.d(TAG, "" + start);
		// if (!start.equals(Constant.toOtherApk)) {
		// SLog.d(TAG, "自己结束");
		// android.os.Process.killProcess(android.os.Process.myPid());
		// }

		super.onStop();
	}

	@Override
	protected void onResume() {
		if (channelList != null && channelList.size() > 0) {
			// 初始化定时器
			executeTime();
		}
		super.onResume();
	}

	class ScreenShotAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return realTimeList.size();
		}

		@Override
		public Object getItem(int position) {
			return realTimeList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHodler hodler = new ViewHodler();
			if (convertView == null) {
				convertView = View.inflate(context,
						R.layout.layout_channel_item, null);
				hodler.screenShot = (ImageView) convertView
						.findViewById(R.id.image_item);
				hodler.netButNoPictrue = (ImageView) convertView
						.findViewById(R.id.net_but_no_pictrue);
				hodler.programName = (TextView) convertView
						.findViewById(R.id.pro_tv);

				hodler.channelName = (TextView) convertView
						.findViewById(R.id.channel_name);
				hodler.startTime = (TextView) convertView
						.findViewById(R.id.pro_time_tv);

				hodler.grogressBar = (ProgressBar) convertView
						.findViewById(R.id.pip_pb);
				hodler.programBackground = (LinearLayout) convertView
						.findViewById(R.id.program_background);
				hodler.noNet = noNetwork;
				convertView.setTag(hodler);
			} else {
				hodler = (ViewHodler) convertView.getTag();
			}
			ProgramDetail pro = null;

			hodler.channelName.setText(channelList.get(position)
					.getChannel_name());
			if (realTimeList != null
					&& realTimeList.get(position).image != null) {
				realTimeList.get(position).image = hodler.screenShot;
				realTimeList.get(position).noPictrue = hodler.netButNoPictrue;
				realTimeList.get(position).noNetwork = hodler.noNet;
				realTimeList.get(position).lastTime = hodler.startTime;
				pro = realTimeList.get(position).pro;
				hodler.grogressBar
						.setProgress(realTimeList.get(position).progress);
			}
			if (pro != null) {
				hodler.programName.setText(pro.getPn());
			}
			return convertView;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (currentGroup.get("currentGroup") != null) {
			currentFive = Integer.valueOf(currentGroup.get("currentGroup"));
		}
		SLog.d(TAG, "===onKeyDown===" + keyCode);
		switch (keyCode) {
		case 185:
			// 按了键盘的a键(29)、黄健(185)
			Intent functionIntent = new Intent();
			functionIntent.setClass(context, FunctionMake.class);
			startActivity(functionIntent);
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			if (ManualToNext && (currentFive + 1) != mapChannels.size()) {
				// 向下按在填充下数据,条件当前显示的是第几组数据
				loadCurrentGroup(String.valueOf((currentFive + 1)));
				Animation downAnimation = AnimationUtils.loadAnimation(this,
						R.anim.slide_in_down);
				channelsLV.startAnimation(downAnimation);
			}
			break;
		case KeyEvent.KEYCODE_DPAD_UP:
			if (currentFive != 0) {
				// 向下按在填充下数据,条件当前显示的是第几组数据
				loadCurrentGroup(String.valueOf((currentFive - 1)));
				Animation upAnimation = AnimationUtils.loadAnimation(this,
						R.anim.slide_in_up);
				channelsLV.startAnimation(upAnimation);
			}
			break;
		case KeyEvent.KEYCODE_DPAD_LEFT:
			if (channelList != null && channelList.size() > 0) {
				String checkCid = channelList.get(which).getChannel_id() + "";
				if (pip != null) {
					// timeline显示
					if (pip.getPopState() && Function.function.get("timeline")) {
						dismissPop();
						Intent intent = new Intent();
						intent.setClass(context, MainActivity.class);
						intent.putExtra("CHA_ID", channelList.get(which)
								.getChannel_id());
						startActivity(intent);
					} else {
						pip.showPop();
					}
				} else {
					pip = new PipPop(context, checkCid);
					pip.showPop();
				}
			}

			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			if (canToNext && ManualToNext && isPopShow()) {
				dismissPop();
				exitScreen();
				Intent intent = new Intent();
				if (Function.function.get("actorInfor")) {
					intent.setClass(context, ProgramActorActivity.class);
				} else {
					intent.setClass(context, ProgramListActivity.class);
				}
				intent.putExtra("CHA_ID", channelList.get(which)
						.getChannel_id());
				intent.putExtra("CHA_NAME", channelList.get(which)
						.getChannel_name());
				startActivity(intent);
			}
			break;
		case KeyEvent.KEYCODE_BACK:
			Intent DSJIntent = getIntent();
			String DSJ = DSJIntent.getStringExtra("StartFrom");// 得到的是电视聚的包名
			try {
				if ("com.babao.tvju".equals(DSJ)) {
					Intent intent = new Intent();
					ComponentName cn = new ComponentName(DSJ,
							"com.babao.tvju.ui.activity.main.MainActivity");
					intent.setComponent(cn);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra("StartFrom", context.getPackageName());
					startActivity(intent);
				}
				android.os.Process.killProcess(android.os.Process.myPid());
			} catch (Exception e) {
			}
			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private Boolean isPopShow() {
		if (pip == null) {
			return true;
		} else {
			return pip.getPopState();
		}
	}
}
